package com.doublefish.doublefishrobot.ui.home;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.bean.DeviceBean;
import com.doublefish.doublefishrobot.ui.home.bean.FirmwareInfoBean;
import com.doublefish.doublefishrobot.ui.home.service.FirmwareService;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.VersionCompareUtils;
import com.doublefish.doublefishrobot.utils.ble.DFBleManager;
import com.doublefish.doublefishrobot.utils.ble.DFS6ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.DFS8ProtocolManager;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.ble.bean.OnBleResponseHandler;
import com.doublefish.doublefishrobot.utils.ble.bean.OnBleWriteFileProgressListner;
import com.doublefish.doublefishrobot.widget.CommonDialog;
import com.doublefish.doublefishrobot.widget.LoadingDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/11/7 16:43
 */
public class DeviceFirmwareActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTv;

    @BindView( R.id.iv_logo)
    ImageView imageView;

    @BindView( R.id.tv_cur_version)
    TextView curVersionTv;

    @BindView( R.id.ll_new_version)
    LinearLayout newVersionLl;

    @BindView( R.id.tv_new_version)
    TextView newVersionTv;

    @BindView( R.id.tv_btn)
    TextView appBtn;

    private DeviceBean deviceBean;
    private FirmwareInfoBean firmwareInfoBean;

    private boolean isUpdatting = false; //是否正固件更新中

    private LoadingDialog loadingDialog;

    public static Intent makeIntent(Activity activity, DeviceBean deviceBean) {
        AppCacheUtil.getInstance().setIntentBean(deviceBean);

        Intent intent = new Intent(activity, DeviceFirmwareActivity.class);
        return intent;
    }

    @Override
    protected void onDestroy() {
        DFBleManager.getInstance().disConnect();
        resetAction();
        super.onDestroy();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_firmware;
    }

    @Override
    protected void initView() {
        titleTv.setText(R.string.firmware_version);
    }

    @Override
    protected void initData() {
        deviceBean = AppCacheUtil.getInstance().getIntentBean();

        if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS8) {
            imageView.setImageResource(R.mipmap.super8_2);
        } else if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS6) {
            imageView.setImageResource(R.mipmap.super6_2);
        }
        //检查蓝牙连接状态
        checkConnectState();
    }

    @Override
    protected void initListener() {

    }


    private void checkConnectState() {
        if (DFBleManager.getInstance().isDidConnectBlueTooth()) {
            //已连接
            if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS6) {
                //获取 超6本地固件版本
                getS6Firmware();
            } else {
                //获取 超8本地固件版本
                getS8Firmware();
            }
            return;
        }
        //先连接
        connectBle();
    }

    private void connectBle() {
        DFBleManager.getInstance().setOnBleManagerListner(new DFBleManager.OnBleManagerListner() {
            @Override
            public void onScanResult(List<DeviceBean> deviceBeanList) {

            }

            @Override
            public void onConnectBle(boolean success, DeviceBean deviceBean) {
                if (success) {
                    showToast(getString(R.string.success_ble));
                    //连接发球机
                    connectMachine();
                } else {
                    showToast(getString(R.string.fail_ble));
                }
            }

            @Override
            public void onDisConnectBle() {
            }
        });
        DFBleManager.getInstance().connectBt(deviceBean.getTid() ,deviceBean.getMac(), deviceBean.getName(), deviceBean.getDeviceType());
    }

    private void connectMachine() {
        if (deviceBean == null) {
            return;
        }
        if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS8) {
            DFS8ProtocolManager.getInstance().connectMachine(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        //获取 超8本地固件版本
                        getS8Firmware();
                    } else {
                        showToast(getString(R.string.fail_get_firmware_tips));
                    }
                    return false;
                }
            });
        } else  if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS6) {
            DFS6ProtocolManager.getInstance().connectMachine(new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        //获取 超6本地固件版本
                        getS6Firmware();
                    } else {
                        showToast(getString(R.string.fail_get_firmware_tips));
                    }
                    return false;
                }
            });
        }
    }

    private void getS8Firmware() {
        DFS8ProtocolManager.getInstance().getFirmwareInfo(new OnBleResponseHandler() {
            @Override
            public boolean onResponse(boolean success, int status, Object res) {
                if (curVersionTv != null) {
                    String version = (String) res;
                    curVersionTv.setText(version);
                    //获取远程固件版本 超8 暂时不做
//                getRemoteFirmwareInfo(1);
                }
                return false;
            }
        });
    }

    private void getS6Firmware() {
        DFS6ProtocolManager.getInstance().getFirmwareInfo(new OnBleResponseHandler() {
            @Override
            public boolean onResponse(boolean success, int status, Object res) {
                if (curVersionTv != null) {
                    String version = (String) res;
                    curVersionTv.setText(version);
                    //获取远程固件版本
                    getRemoteFirmwareInfo(version, 2);
                }
                return false;
            }
        });
    }

    //deviceType  型号 int  1.超8  2.超6
    private void getRemoteFirmwareInfo(String localVer, int deviceType) {
        // FIXME: 2025/2/17 暂时不做升级
        if (true) {
            return;
        }
        //model  型号 int  1.超8  2.超6
        int model = deviceType;
        FirmwareService.getFirmwareVersion(this, model, new FirmwareService.OnFirmwareServiceCallback() {
            @Override
            public void onNetworkPermissionError() {
                showNetworkPermissionAlert();
            }

            @Override
            public void onSuccess(FirmwareInfoBean bean) {
                firmwareInfoBean = bean;

                newVersionLl.setVisibility(View.VISIBLE);
                newVersionTv.setText(bean.getVer());
                if (VersionCompareUtils.compare(localVer, bean.getVer()) == 1) {
                    appBtn.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(String err) {
                Log.i("onFailure", err);
                showToast(err);
            }
        });
    }

    @OnClick(R.id.ll_back)
    public void onBackBtnClick() {
        if (isUpdatting) {
            //更新中禁止返回
            return;
        }
        finish();
    }

    @Override
    public void onBackPressed() {
        if (isUpdatting) {
            //更新中禁止返回
            return;
        }
        super.onBackPressed();
    }

    @OnClick(R.id.tv_btn)
    public void onVersionBtnClick() {
        String title = getString(R.string.update_firmware_tips_1);
        String msg =  getString(R.string.update_firmware_tips_2);
        CommonDialog dialog = new CommonDialog(this, title, msg, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                setUpdattingAction();
                checkFirmwareFile();
            }
        });
        dialog.show();
    }

    private void checkFirmwareFile() {
        showLoadingDialog(getString(R.string.checking_firmware_tips));

        FirmwareService.checkBinIsExist(this, firmwareInfoBean, new FirmwareService.OnFirmwareBinExistCallback() {
            @Override
            public void onCalback(boolean suc, String path, String hash) {
                if (suc) {
                    //传输文件
                    sendFile(path, hash);
                } else {
                    //下载文件
			         downloadFile(firmwareInfoBean.getPath() ,path, firmwareInfoBean.getHash());
                }
            }
        });
    }

    private void sendFile(String path, String hash) {
        showLoadingDialog(getString(R.string.updatting_firmware_progress) + " 0%");

        if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS8) {
            DFS8ProtocolManager.getInstance().writeFile(0, "update.bin", path, new OnBleWriteFileProgressListner() {
                @Override
                public void onProgress(int pro) {
                    showLoadingDialog(getString(R.string.updatting_firmware_progress) + " " + pro + "%");
                }
            }, new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        sendHashCode(hash);
                    } else {
                        resetAction();
                        showToast(getString(R.string.fail_update_firmware_tips));
                    }

                    return false;
                }
            });
        } else if (deviceBean.getDeviceType() == ModeConstant.DeviceTypeS6) {
            DFS6ProtocolManager.getInstance().writeFile(0, "update.bin", path, new OnBleWriteFileProgressListner() {
                @Override
                public void onProgress(int pro) {
                    showLoadingDialog(getString(R.string.updatting_firmware_progress) + " " + pro + "%");
                }
            }, new OnBleResponseHandler() {
                @Override
                public boolean onResponse(boolean success, int status, Object res) {
                    if (success) {
                        sendHashCode(hash);
                    } else {
                        resetAction();
                        showToast(getString(R.string.fail_update_firmware_tips));
                    }
                    return false;
                }
            });
        }
    }

    //下载升级文件
    private void downloadFile(String url,String path, String hash) {
        showLoadingDialog(getString(R.string.downloading_firmware_progress) + " 0%");
        FirmwareService.downloadFile(this, url, path, hash, new FirmwareService.OnFirmwareDownloadCallback() {
            @Override
            public void onNetworkPermissionError() {
                resetAction();
                showNetworkPermissionAlert();
            }

            @Override
            public void onProgress(int size) {
                int percent = size * 100 / firmwareInfoBean.getSize();
                String text = getString(R.string.downloading_firmware_progress) + " "+ percent + "%";
                showLoadingDialog(text);
            }

            @Override
            public void onCalback(boolean suc, String msg) {
                if (suc) {
                    sendFile(path,hash);
                } else {
                    resetAction();
                    showToast(msg);
                }
            }
        });
    }

    private void sendHashCode(String hash) {
        //用写script 的接口 写hashcode
        DFS8ProtocolManager.getInstance().writeScript(0, "hash.txt", hash, new OnBleResponseHandler() {
            @Override
            public boolean onResponse(boolean success, int status, Object res) {
                resetAction();
                if (success) {
                    showSendFinishAlert();
                } else {
                    resetAction();
                    showToast(getString(R.string.fial_send_verification_file_tips));
                }

                return false;
            }
        });
    }

    //更新状态
    private void setUpdattingAction() {
        isUpdatting = true;
        keepBright(true);
    }
    //重置庄涛
    private void resetAction() {
        isUpdatting = false;
        keepBright(false);
        hideLoadingDialog();
    }

    //保持屏幕常亮
    private void keepBright(boolean bright) {
        if (bright) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }

    private void showLoadingDialog(String msg) {
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this);
        }
        loadingDialog.setMsg(msg);
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    private void hideLoadingDialog() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    private void showSendFinishAlert() {
        CommonDialog commonDialog = new CommonDialog(this,  getString(R.string.success_update_firmware_tips), null, null);
        commonDialog.setShowNegativeButton(false);
        commonDialog.show();
    }

    private void showNetworkPermissionAlert() {
//        String title = "网络错误";
//        String msg = "请检查网络";
//        CommonDialog dialog = new CommonDialog(this, title, msg, null);
//        dialog.setShowNegativeButton(false);
//        dialog.show();

        showToast(getString(R.string.network_error));
    }
}


